package com.jgp.sys.ui;

import com.jgp.sys.query.OrderList;
import com.jgp.sys.query.jpa.CriteriaExpression;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.Objects;

/**
 * 项目   jgp
 * 作者   loufei
 * 时间   2017/10/18
 */
public class Pager {
    private int current;
    private int pageSize;
    private long totalCount;
    private long totalPageCount;

    public Pager() {
    }

    public Pager(int current, int pageSize) {
        this.current = current;
        this.pageSize = pageSize;
    }

    public int getCurrent() {
        return current;
    }

    public void setCurrent(int current) {
        this.current = current;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
        updatePageCount();
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        this.totalCount = totalCount;
        updatePageCount();
    }

    public long getTotalPageCount() {
        return totalPageCount;
    }

    public void setTotalPageCount(long totalPageCount) {
        this.totalPageCount = totalPageCount;
    }
    
    private void updatePageCount(){
        if(Objects.isNull(totalCount)||Objects.isNull(pageSize)) return;
        float per = totalCount % pageSize;
        setTotalPageCount(per != 0 ? (totalCount / pageSize + 1) : totalCount / pageSize);
    }
    
    public Pageable pageable(OrderList orders){
        Pageable pageable;
        if (Objects.nonNull(orders) && orders.size() > 0) {
            pageable = PageRequest.of(this.getCurrent() - 1, this.getPageSize(), CriteriaExpression.toSort(orders));
        } else {
            pageable = PageRequest.of(this.getCurrent() - 1, this.getPageSize());
        }
        return pageable;
    }
}
